package hm.telephoneoperator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import br.hm.telephoneoperator.CallOperatorException;
import br.hm.telephoneoperator.CallOperatorService;
import br.hm.telephoneoperator.Phone;
import br.hm.telephoneoperator.PhonePortabilityDetail;
import br.hm.telephoneoperator.impl.HtmlCallOperatorService;
import br.hm.util.PhoneUtils;

public class ContactTelephoneOperatorActivity extends ListActivity {

	private Handler handler = new Handler();
	private CallOperatorService callOperatorService = new HtmlCallOperatorService();
	private PhonePortabilityDetailAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		adapter = new PhonePortabilityDetailAdapter(this);
		setListAdapter(adapter);

		ProgressDialog progressDialog = ProgressDialog.show(this, "Operadora",
				"Buscando Operadora, favor aguardar...", false, true);
		processThread(progressDialog);
	}

	private void processThread(final ProgressDialog progressDialog) {
		new Thread() {
			@Override
			public void run() {
				try {

					Cursor cursor = getContentResolver().query(
							Contacts.Phones.CONTENT_URI,
							new String[] { Contacts.PhonesColumns.NUMBER,
									Contacts.PhonesColumns.NUMBER_KEY,
									Contacts.PeopleColumns.NAME }, null, null,
							null);

					startManagingCursor(cursor);
					List<Phone> phones = new ArrayList<Phone>();
					while (cursor.moveToNext()) {
						String number = cursor.getString(0);
						String label = cursor.getString(1);
						try {
							Phone phone = PhoneUtils.parser(number, "81", "55");

							phones.add(phone);
							Log.i("TESTE", phone.toString());
							Log.i("TESTE", "label [" + label + "]");
						} catch (java.text.ParseException e) {
							Log.i("TESTE", "Erro ao converter [" + number + "]");
						}
					}

					final List<PhonePortabilityDetail> phonePortabilityDetails = callOperatorService
							.getLastPhonePortabilityDetail(phones);
					handler.post(new Runnable() {

						@Override
						public void run() {
							adapter.setPhonePortabilityDetails(phonePortabilityDetails);
						}
					});

				} catch (final CallOperatorException e) {
					handler.post(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(
									ContactTelephoneOperatorActivity.this,
									"Problema ao solicitar dados da operadora - "
											+ e.getMessage(), Toast.LENGTH_LONG)
									.show();
							Log.e(getString(R.string.app_name), e.getMessage());
							finish();
						}
					});

				} finally {
					handler.post(new Runnable() {

						@Override
						public void run() {
							progressDialog.dismiss();
						}
					});
				}
			}
		}.start();
	}

}

class PhonePortabilityDetailAdapter extends BaseAdapter {

	private Context context;
	@SuppressWarnings("unchecked")
	private List<PhonePortabilityDetail> phonePortabilityDetails = Collections.EMPTY_LIST;

	public PhonePortabilityDetailAdapter(Context context) {
		this.context = context;
	}

	@Override
	public int getCount() {
		return this.phonePortabilityDetails.size();
	}

	@Override
	public Object getItem(int index) {
		return this.phonePortabilityDetails.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int index, View convertView, ViewGroup vg) {
		PhonePortabilityDetail portabilityDetail = this.phonePortabilityDetails
				.get(index);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.layout_contact_operator, null);
		if (index % 2 == 0) {
			v.setBackgroundResource(R.color.color_table_row_par);
		} else {
			v.setBackgroundResource(R.color.color_table_row_odd);
		}
		TextView numbeTextView = (TextView) v.findViewById(R.id.phone_number);
		TextView operatorTextView = (TextView) v
				.findViewById(R.id.phone_operator);
		numbeTextView.setText(portabilityDetail.getPhone().toString());
		operatorTextView
				.setText(portabilityDetail.getPhoneOperator().getName());
		return v;
	}

	public void setPhonePortabilityDetails(
			List<PhonePortabilityDetail> phonePortabilityDetails) {
		this.phonePortabilityDetails = phonePortabilityDetails;
		notifyDataSetChanged();
	}

}
